package com.cuitrip.business.user;

import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;

import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.business.user.proxy.UserInfoProxy;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.component.page.SimpleEmptyFragmentActivity;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.PlatformUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.jumper.Jumper;
import com.lab.network.config.CtResponseCode;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;

import butterknife.ButterKnife;
import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by MiJack on 2015/10/16.
 */
public class CertActivity extends CustomUiFragmentActivity implements IProxyCallback {

    public static final int REQUEST_CODE_CHANGE_EMAIL = 0xc17;
    private static final int REQUEST_CODE_CERT_EMAIL = 201;
    private static final int REQUEST_CODE_CERT_PHONE = 202;
    @Bind(R.id.layoutPhone)
    ItemLayout textPhone;
    @Bind(R.id.layoutEmail)
    ItemLayout textEmail;
    @Bind(R.id.layoutIdentity)
    ItemLayout textIdentity;
    @Bind(R.id.social_account)
    ItemLayout socialAccount;
    private ApiProxy apiProxy;
    private CtUserInfo mUserInfo = null;
    @Bind(R.id.state_layout)
    StateLayout mStateLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.ct_activity_cert);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        apiProxy = new ApiProxy(this);
    }

    @Override
    public void initListener() {
        mStateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                requestUserCertInfo();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestUserCertInfo();
    }

    private void requestUserCertInfo() {
        mStateLayout.changeState(StateLayout.State.Loading);
        CtUserInfo info = LoginInstance.getInstance().getUserInfo();
        UserBusiness.getUserInfo(apiProxy,info.getUid());
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if(response!=null && response.code == CtResponseCode.RESULT_OK){
            mStateLayout.changeState(StateLayout.State.INIT);
            if (response.result != null && response.result instanceof CtUserInfo) {
                mUserInfo = ((CtUserInfo) response.result);
                CtUserInfo user = LoginInstance.updateProfile(AppCoreRuntime.context, mUserInfo, false);
                bindData(user);
            }
        }else{
            mStateLayout.changeState(StateLayout.State.NoNetwork);
            hideNoCancelDialog();
            String msg;
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                msg = response.msg;
            } else {
                msg = PlatformUtil.getInstance().getString(R.string.feedback_data_err);
            }
            MessageUtils.showToast(msg);
        }
        return false;
    }

    private void bindData(final CtUserInfo userInfo) {
        if (!userInfo.isEmailValidated()){
            textEmail.setmRightText(getString(R.string.user_verify_state_0));
        }else{
            textEmail.setmRightText(userInfo.getEmail());
        }
        SpannableStringBuilder charSequence = UserInfoProxy.getInstance().getSocialBindBuilder(userInfo);
        charSequence.setSpan(new AbsoluteSizeSpan(21, true), 0, charSequence.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        socialAccount.setmRightText(charSequence);
        socialAccount.getmRightTextView().setTag("font:icon");
        String phone = userInfo.getMobile();
        String countryCode = userInfo.getCountryCode();
        textPhone.setmRightText(
                TextUtils.isEmpty(phone)?getString(R.string.value_no_set)
                        : ((TextUtils.isEmpty(countryCode) ? "" : ("+" + countryCode + " ")) + phone)
        );
        ItemLayout layoutIdentity = (ItemLayout) findViewById(R.id.layoutIdentity);
        String identity = getIndentityString();
        //审核中或者审核通过无法点击
        if (userInfo.getIdCheckStatus() == CtUserInfo.ID_CHECK_ING
                || userInfo.getIdCheckStatus() == CtUserInfo.ID_CHECK_SUC) {
            layoutIdentity.setOnClickListener(null);
            layoutIdentity.setEnabled(false);
            layoutIdentity.setShowRightIcon(false);
            if (userInfo.getIdCheckStatus() == CtUserInfo.ID_CHECK_SUC){
                TrackUtil.trackScreenName("/user/verification/verified");
            }

        } else {
            layoutIdentity.setShowRightIcon(true);
            layoutIdentity.setEnabled(true);
            layoutIdentity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String[] pics = null;
                    String pic1 = "";
                    String pic2 = "";
                    LogHelper.e("pics", "" + userInfo.getIdPictures());
                    if (!TextUtils.isEmpty(userInfo.getIdPictures())) {
                        pics = userInfo.getIdPictures().split(",");
                        LogHelper.e("pics", TextUtils.join("-", pics));
                        if (pics != null && pics.length >= 2) {
                            pic1 = pics[0];
                            pic2 = pics[1];
                        }
                    }
                    LogHelper.e("pics", pic1 + "   " + pic2);
                    TrackUtil.trackScreenName("/user/verification/id");
                    SelfIdentificationActivity.start(CertActivity.this, userInfo.getIdRefuseReason(),
                            userInfo.getIdArea(), userInfo.getIdType(), userInfo.getIdNumber(),
                            userInfo.getIdValidTime(), userInfo.getRealName(), userInfo.getGender(), userInfo.getBirthDay(), pic1, pic2);
                }
            });
        }
        //                  验证通过：前六位+6个*+后4位
        //                         number为空：显示"验证通过"
        //                         不足10位 、 大于4位，length/2-1+**+length/2+1
        //                            其余显示验证通过
        if (userInfo.getIdCheckStatus() == CtUserInfo.ID_CHECK_SUC) {
            String number = userInfo.getIdNumber();
            textIdentity.setmRightText(getString(R.string.user_verify_state_2));
            if (number != null) {
                if (number.length() > 10) {
                    String content = number.substring(0, 6) + "******" + number.substring(number.length() - 4);
                    textIdentity.setmRightText(content);
                } else if (number.length() > 4) {
                    String content = number.substring(0, number.length() / 2 - 1) + "**" + number.substring(number.length() / 2 + 1);
                    textIdentity.setmRightText(content);
                }
            }
        } else {
            textIdentity.setmRightText(identity);
        }
    }


    public String getIndentityString() {
        if (mUserInfo.getIdCheckStatus() < 0) {
            return getString(R.string.user_verify_state_0);
        }
        switch (mUserInfo.getIdCheckStatus()) {
            case CtUserInfo.ID_CHECK_ING:
                return getString(R.string.user_verify_state_1);
            case CtUserInfo.ID_CHECK_SUC:
                return getString(R.string.user_verify_state_2);
            case CtUserInfo.ID_CHECK_FAILED:
                return getString(R.string.trip_state_rejected);
            case CtUserInfo.ID_CHECK_NONE:
                return getString(R.string.user_verify_state_0);
        }
        return getString(R.string.user_verify_state_0);
    }

    @OnClick(R.id.layoutPhone)
    void certPhone() {
        Bundle bundle=new Bundle();
        TrackUtil.trackScreenName("/user/verification/phone");
        bundle.putInt(ShowCertInfoFragment.SHOW_CERT_KEY,ShowCertInfoFragment.SHOW_CERT_PHONE);
        SimpleEmptyFragmentActivity.startFragmentActivityForResult(this,ShowCertInfoFragment.class,bundle, 1);
    }
    /**
     * 点击，验证邮箱
     */
    @OnClick(R.id.layoutEmail)
    void certEmail() {
        TrackUtil.trackScreenName("/user/verification/email");
        Bundle bundle=new Bundle();
        bundle.putInt(ShowCertInfoFragment.SHOW_CERT_KEY,ShowCertInfoFragment.SHOW_CERT_EMAIL);
        SimpleEmptyFragmentActivity.startFragmentActivityForResult(this,ShowCertInfoFragment.class,bundle, 1);
    }

    @OnClick(R.id.social_account)
    void navigate2SocialBind() {
        TrackUtil.trackScreenName("/user/verification/sns");
        Intent intent = new Intent(this, SocialBindActivity.class);
        intent.putExtra(SocialBindActivity.USER_KEY, mUserInfo);
        Jumper.launchActivity(this, intent);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mUserInfo = LoginInstance.getInstance().getUserInfo();
        requestUserCertInfo();
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.user_group_verification);
        return config;
    }

    @Override
    public void onTopbarLeftPress() {
        onBackPressed();
    }
}
